package com.yuanqi.controller;

import com.yuanqi.domain.OrderTracking;
import com.yuanqi.repository.OrderTrackingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 订单跟踪控制器
 * @author 王瑞杰
 */
@RestController
@RequestMapping("/api/retail/tracking")
@CrossOrigin(origins = "*")
public class OrderTrackingController {
    
    @Autowired
    private OrderTrackingRepository orderTrackingRepository;
    
    /**
     * 创建跟踪记录
     */
    @PostMapping
    public ResponseEntity<OrderTracking> createTracking(@RequestBody OrderTracking tracking) {
        try {
            tracking.setTimestamp(LocalDateTime.now());
            tracking.setCreatedAt(LocalDateTime.now());
            OrderTracking savedTracking = orderTrackingRepository.save(tracking);
            return ResponseEntity.ok(savedTracking);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 根据ID查找跟踪记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<OrderTracking> getTracking(@PathVariable Long id) {
        Optional<OrderTracking> tracking = orderTrackingRepository.findById(id);
        return tracking.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 根据订单ID查找跟踪记录
     */
    @GetMapping("/order/{orderId}")
    public ResponseEntity<List<OrderTracking>> getTrackingByOrderId(@PathVariable Long orderId) {
        List<OrderTracking> trackingList = orderTrackingRepository.findByOrderIdOrderByTimestampAsc(orderId);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 根据状态类型查找跟踪记录
     */
    @GetMapping("/status-type/{statusType}")
    public ResponseEntity<List<OrderTracking>> getTrackingByStatusType(@PathVariable String statusType) {
        List<OrderTracking> trackingList = orderTrackingRepository.findByStatusTypeOrderByTimestampDesc(statusType);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 根据订单类型查找跟踪记录
     */
    @GetMapping("/type/{orderType}")
    public ResponseEntity<List<OrderTracking>> getTrackingByOrderType(@PathVariable String orderType) {
        List<OrderTracking> trackingList = orderTrackingRepository.findByOrderTypeOrderByTimestampDesc(orderType);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 根据状态查找跟踪记录
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<OrderTracking>> getTrackingByStatus(@PathVariable String status) {
        List<OrderTracking> trackingList = orderTrackingRepository.findByStatusOrderByTimestampDesc(status);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 根据操作员查找跟踪记录
     */
    @GetMapping("/operator/{operatorId}")
    public ResponseEntity<List<OrderTracking>> getTrackingByOperator(@PathVariable Long operatorId) {
        List<OrderTracking> trackingList = orderTrackingRepository.findByOperatorIdOrderByTimestampDesc(operatorId);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 根据日期范围查找跟踪记录
     */
    @GetMapping("/date-range")
    public ResponseEntity<List<OrderTracking>> getTrackingByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            LocalDateTime start = LocalDateTime.parse(startDate + "T00:00:00");
            LocalDateTime end = LocalDateTime.parse(endDate + "T23:59:59");
            List<OrderTracking> trackingList = orderTrackingRepository.findByTimestampBetween(start, end);
            return ResponseEntity.ok(trackingList);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 分页查找跟踪记录
     */
    @GetMapping
    public ResponseEntity<Page<OrderTracking>> getTracking(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<OrderTracking> trackingPage = orderTrackingRepository.findAll(pageable);
        return ResponseEntity.ok(trackingPage);
    }
    
    /**
     * 查找订单的最新跟踪记录
     */
    @GetMapping("/order/{orderId}/latest")
    public ResponseEntity<List<OrderTracking>> getLatestTrackingByOrderId(@PathVariable Long orderId) {
        List<OrderTracking> trackingList = orderTrackingRepository.findLatestByOrderId(orderId);
        return ResponseEntity.ok(trackingList);
    }
    
    /**
     * 查找订单的最新状态
     */
    @GetMapping("/order/{orderId}/latest-status")
    public ResponseEntity<OrderTracking> getLatestStatusByOrderId(@PathVariable Long orderId) {
        OrderTracking tracking = orderTrackingRepository.findLatestStatusByOrderId(orderId);
        return tracking != null ? ResponseEntity.ok(tracking) : ResponseEntity.notFound().build();
    }
    
    /**
     * 查找进行中的订单
     */
    @GetMapping("/active-orders")
    public ResponseEntity<List<Long>> getActiveOrderIds() {
        List<Long> orderIds = orderTrackingRepository.findActiveOrderIds();
        return ResponseEntity.ok(orderIds);
    }
    
    /**
     * 查找今日配送的订单
     */
    @GetMapping("/today-delivery")
    public ResponseEntity<List<Long>> getTodayDeliveryOrderIds() {
        List<Long> orderIds = orderTrackingRepository.findTodayDeliveryOrderIds();
        return ResponseEntity.ok(orderIds);
    }
    
    /**
     * 获取跟踪统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Object> getTrackingStatistics() {
        try {
            Long todayTracking = orderTrackingRepository.countTodayTracking();
            List<Long> activeOrderIds = orderTrackingRepository.findActiveOrderIds();
            List<Long> todayDeliveryOrderIds = orderTrackingRepository.findTodayDeliveryOrderIds();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("todayTracking", todayTracking);
            statistics.put("activeOrders", activeOrderIds.size());
            statistics.put("todayDelivery", todayDeliveryOrderIds.size());
            
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
